[gcode_macro M702]                                              # Marlin Compatibility  (FILAMENT_UNLOAD?)
description: Unload filament
gcode:
  {% set default_u = 100 %}

  {% if 'save_variables' in printer %}
    {% set svv = printer.save_variables.variables %}
    {% if 'bowden_len' in svv %}
      {% set default_u = svv.bowden_len %}
    {% endif %}
  {% endif %}

  {% set p = params.P|default(8)|float %}
  {% set p_f = params.PF|default(180)|float %}
  {% set i = params.I|default(30)|float %}
  {% set i_f = params.IF|default(180)|float %}
  {% set u = params.U|default(default_u)|float %}
  {% set u_f = params.UF|default(360)|float %}

  {% if printer.idle_timeout.state == "Printing" and not printer.pause_resume.is_paused %}
    {action_respond_info("This command cannot be used while printing")}
  {% elif printer.extruder.temperature < 170 %}
    {action_respond_info("Extruder temperature too low")}
  {% else %}
    SAVE_GCODE_STATE NAME=M702_state
    M83
    {% if p > 0.0 %}
      G1 E{p} F{p_f}
    {% endif %}
    {% if i > 0.0 %}
      G1 E-{i} F{i_f}
    {% endif %}
    {% if u > 0.0 %}
      G1 E-{u} F{u_f}
    {% endif %}
    RESTORE_GCODE_STATE NAME=M702_state MOVE=0
  {% endif %}
